import { Base64 } from './base64.js'

//比较版本号
const compareVersion = (v1, v2) => {
	v1 = v1.split('.')
	v2 = v2.split('.')
	const len = Math.max(v1.length, v2.length)

	while (v1.length < len) {
		v1.push('0')
	}
	while (v2.length < len) {
		v2.push('0')
	}

	for (let i = 0; i < len; i++) {
		const num1 = parseInt(v1[i])
		const num2 = parseInt(v2[i])

		if (num1 > num2) {
			return 1
		} else if (num1 < num2) {
			return -1
		}
	}

	return 0
}

//去空格
const trimStr = str => {
	return str.replace(/(^\s*)|(\s\r\n*$)/g, "");
}

//验证手机号
const checkPhone = data => {
	const TEL_REGEXP = /^1[3456789]\d{9}$/
	// /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/
	return TEL_REGEXP.test(data)
}

// 验证座机号
const checkTel = data => {
	const TEL_REGEXP = /^\d{3,4}-?\d{7,9}$/
	// /^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/
	return TEL_REGEXP.test(data)
}

// 计算事件差
const haveTimer = (faultDate, completeTime) => { //传值为时间戳
	var stime = new Date().getTime();
	var etime = new Date().getTime();
	if (faultDate) {
		var stime = faultDate;
	}
	if (completeTime) {
		var etime = completeTime;
	}
	var restSec = etime - stime; //两个时间戳相差的毫秒数
	let day = parseInt(restSec / (60 * 60 * 24 * 1000))
	let hour = parseInt(restSec / (60 * 60 * 1000) % 24)
	let minu = parseInt(restSec / (60 * 1000) % 60)
	let sec = parseInt(restSec / 1000 % 60)
	let timeObj = {
		day: day < 10 ? '0' + day : day,
		hour: hour < 10 ? '0' + hour : hour,
		minu: minu < 10 ? '0' + minu : minu,
		sec: sec < 10 ? '0' + sec : sec
	}
	return timeObj
}


// 函数节流和函数防抖封装在了一个函数里，通过第三个参数切换模式
const throttle = function(fn, delay, isDebounce) {
	let timer
	let lastCall = 0
	return (function(...args) {
		if (isDebounce) {
			if (timer) clearTimeout(timer)
			timer = setTimeout(() => {
				fn(...args)
			}, delay)
		} else {
			const now = new Date().getTime()
			if (now - lastCall < delay) return
			lastCall = now
			fn(...args)
		}
	})
}

/**
 * 时间戳转时间格式
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
const parseTime = (time, cFormat) => {
	if (!time) return
	if (arguments.length === 0) {
		return null
	}
	const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') {
			return ['日', '一', '二', '三', '四', '五', '六'][value]
		}
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}

/**
 * 时间格式转时间戳
 * date格式为日期格式
 * 例如：2019-08-14 11:57
 */
const timeStamp = (date) => {
	const time1 = date.replace(/-/g, '/')
	const time2 = new Date(time1)

	return Date.parse(time2)
}


/**
 * base64 加密、解密
 * parameter 参数
 * type true加密 false解密
 */
const baseCrypto = (parameter, type = true) => {

  if (type) {
    return Base64.encode(JSON.stringify(parameter))
  } else {
    return Base64.decode(parameter)
  }
}

/**
 * driveId=1&driveId=1转JSON
 * variable 参数
 */
const getQueryVariable = (variable) => {
	let vars = variable.split("&");
	let pairObj = {}
	for (let i=0; i<vars.length; i++) {
	   let pair = vars[i].split("=");
	   pairObj[pair[0]] = pair[1]
	}

	return pairObj;
}


module.exports = {
	compareVersion,
	trimStr,
	checkPhone,
	checkTel,
	haveTimer,
	throttle,
	parseTime,
	timeStamp,
	baseCrypto,
	getQueryVariable
}
